# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
  include CalendarHelper

  def logged_in?
    current_user != :false
  end

  def current_user
    @current_user ||= (session[:user] && User.find_by_id(session[:user])) || :false
  end

  def is_admin?
    return true if not current_user.is_a?(Symbol) and current_user[:kind] == 'Admin'
    false
  end

  alias is_administrator? is_admin?

  def is_student?
    return true if not current_user.is_a?(Symbol) and current_user[:kind] == 'Student'
    false
  end

  def is_instructor?
    return true if not current_user.is_a?(Symbol) and current_user[:kind] == 'Instructor'
    false
  end

  # Es igual a error_messages_for pero con los mensajes en español.
  def mensajes_de_error_para(*params)
    options = params.last.is_a?(Hash) ? params.pop.symbolize_keys : {}
    objects = params.collect {|object_name| instance_variable_get("@#{object_name}") }.compact
    count   = objects.inject(0) {|sum, object| sum + object.errors.count }
    unless count.zero?
      html = {}
      [:id, :class].each do |key|
        if options.include?(key)
          value = options[key]
          html[key] = value unless value.blank?
        else
          html[key] = 'errorExplanation'
        end
      end
      header_message = "Se encontraron algunos errores: "
      error_messages = objects.map {|object| object.errors.full_messages.map {|msg| content_tag(:li, msg) } }
      content_tag(:div,
                  content_tag(options[:header_tag] || :h2, header_message) <<
                      content_tag(:ul, error_messages),
                  html)
    else
           ''
    end
  end

  def date_spanish(dattime, include_hour = false)
    s = dattime.mday.to_s + " "
    s += %w(Enero Febrero Marzo Abril Mayo Junio Julio Agosto Septiembre Octubre Noviembre Diciembre)[dattime.month-1] + " "
    s += dattime.year.to_s
    s += dattime.strftime " %H:%M:%S" if include_hour
    s
  end

  def hide_on_click(texto, id)
    "<span onclick=\"if ( !$('#{id}').visible ) { Effect.SlideDown('#{id}'); $('#{id}').visible = true; } else { Effect.SlideUp('#{id}'); $('#{id}').visible = false; };return false;\">" +
      texto +
      "</span>"
  end

end
